(function() {
  'use strict';

  angular.module('mlApp.login', [])
    .config(['$stateProvider', LoginConfig])
    .controller('LoginController', ['$state', '$q', 'ConsumerService', 'SessionsService', LoginController]);

  function LoginConfig($stateProvider) {
    $stateProvider
      .state('login', {
        url: '/login',
        templateUrl: 'modules/login/login.html',
        controller: 'LoginController',
        controllerAs: 'vm'
      });
  }

  function LoginController($state, $q, ConsumerService, SessionsService) {
    var vm = this;

    vm.captcha = {
      image: '',
      captchaId: '',
      isChecking: false
    };
    vm.loginForm = {
      username: '',
      password: '',
      captchaCode: '',
      captchaId: ''
    };
    vm.validForm = {
      isSubmiting: false,
      captchaCode: '',
      username: '',
      password: '',
      msg: ''
    };

    vm.createCaptcha = createCaptcha;
    vm.checkCaptcha = checkCaptcha;
    vm.loginEnter = loginEnter;
    vm.login = login;

    activate();

    /////////////////////////////////////////

    function activate() {
      createCaptcha();
    }

    function createCaptcha() {
      SessionsService.loadCaptcha().then(function(result) {
        vm.captcha = {
          image: 'data:image/png;base64,' + result.imageBase64,
          captchaId: result.captchaId,
          isChecking: false
        };
        vm.loginForm.captchaId = result.captchaId;
      }, function(msg) {
        console.log(msg);
      });
    }

    function loginEnter(e) {
      var keycode = window.event ? e.keyCode : e.which;
      if (keycode == 13) {
        login();
      } else if (vm.loginForm.captchaCode.length == 4) {
        checkCaptcha();
      }
    }

    function checkCaptcha() {
      return $q(function(resolve, reject) {
        var data = {
          captchaId: vm.captcha.captchaId,
          captchaCode: vm.loginForm.captchaCode,
        };
        if (vm.loginForm.captchaCode && vm.captcha.isChecking === false) {
          vm.captcha.isChecking = true;
          SessionsService.checkCaptcha(data).then(function(result) {
            vm.captcha.isChecking = false;
            vm.validForm.msg = '';
            resolve();
          }, function(msg) {
            vm.captcha.isChecking = false;
            vm.validForm.msg = msg;
            reject();
          });
        } else {
          reject();
        }
      });
    }

    function validForm() {
      var valid = true;

      if (vm.loginForm.username === '') {
        vm.validForm.username = 'empty';
      }

      if (vm.loginForm.password === '') {
        vm.validForm.password = 'empty';
      }

      if (vm.loginForm.captchaCode === '') {
        vm.validForm.captchaCode = 'empty';
      }

      if (vm.validForm.username !== '' || vm.validForm.password !== '' || vm.validForm.captchaCode !== '') {
        valid = false;
      }
      return valid;
    }

    function login() {
      if (vm.validForm.isSubmiting === false && validForm()) {
        checkCaptcha().then(function() {
          vm.validForm.isSubmiting = true;
          SessionsService.login(vm.loginForm).then(function(userInfo) {
            vm.validForm.isSubmiting = false;
            $state.go('menu');
          }, function(msg) {
            createCaptcha();
            vm.validForm.isSubmiting = false;
            vm.loginForm.captchaCode = '';
            vm.validForm.msg = msg;
          });
        });
      }
    }
  }
})();